package com.example.textview;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class CameraActivity extends AppCompatActivity   {
    private Camera.Size previewSize;
    private Integer rgbCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
    private boolean isPreview=false;
    private Camera camera;
    private SurfaceView surfaceView;
    private int additionalRotation;
    private int displayOrientation = 0;

    private Point previewViewSize;

    private Point specificPreviewSize;

    Boolean aBoolean=false;
    ImageView mimageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(R.layout.activity_camera);

        /*************  ****************/

//        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
//                WindowManager.LayoutParams. FLAG_FULLSCREEN);

        surfaceView=findViewById(R.id.surfaceView);
        final SurfaceHolder surfaceHolder =surfaceView.getHolder();
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mimageView=findViewById(R.id.imageView);
        ImageButton preview = findViewById(R.id.preview);



        Button btn3=findViewById(R.id.button3);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aBoolean=true;
            }
        });


        preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isPreview)
                {
                 int   mCameraId = Camera.getNumberOfCameras() - 1;
                    rgbCameraID=0;
                  camera=Camera.open(0);
                  isPreview=true;


                }
                try {

                    Camera.Size lastPreviewSize = previewSize;
                    previewSize = camera.getParameters().getPreviewSize();


                    displayOrientation = getCameraOri(getWindowManager().getDefaultDisplay().getRotation());
                    camera.setDisplayOrientation(displayOrientation);


                    camera.setPreviewDisplay(surfaceHolder);
                    Camera.Parameters parameters=camera.getParameters();

                    previewViewSize=new Point(surfaceView.getMeasuredWidth(), surfaceView.getMeasuredHeight());

                    List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
                    if (supportedPreviewSizes != null && supportedPreviewSizes.size() > 0) {
                        previewSize = getBestSupportedSize(supportedPreviewSizes, previewViewSize);
                    }



                    parameters.setPictureFormat(PixelFormat.JPEG);
                    parameters.set("jpeg-quality",80);

                    parameters.setPreviewSize(previewSize.width, previewSize.height);
                    camera.setParameters(parameters);
                    camera.setPreviewCallback(new Camera.PreviewCallback() {
                        @Override
                        public void onPreviewFrame(byte[] bytes, Camera camera) {

                            if(aBoolean)
                            {

//                                for(int i=0;i<bytes.length;i++)
//                                {
//
//                                    Log.d("TEST","数据："+i+": "+bytes[i]);
//                                }
                                Bitmap bitmap=  runInPreviewFrame(bytes,camera);
                                Matrix m = new Matrix();
                                m.postRotate(270);
                                // bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
                                mimageView.setImageBitmap(bitmap);
                                aBoolean=false;

                            }
                        }
                    });
                    camera.startPreview();
                    camera.autoFocus(null);



                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        ImageButton takePicture = findViewById(R.id.takephote);
        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //实现拍照
                if(camera!=null)
                {
                    camera.takePicture(null,null,jpeg);
                    resetCamera();

                }

            }
        });




    }


    final   Camera.PictureCallback jpeg=new Camera.PictureCallback(){
        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            camera.stopPreview();
            isPreview=false;

        }
    };

    private Camera.Size getBestSupportedSize(List<Camera.Size> sizes, Point previewViewSize) {
        if (sizes == null || sizes.size() == 0) {
            return camera.getParameters().getPreviewSize();
        }
        Camera.Size[] tempSizes = sizes.toArray(new Camera.Size[0]);
        Arrays.sort(tempSizes, new Comparator<Camera.Size>() {
            @Override
            public int compare(Camera.Size o1, Camera.Size o2) {
                if (o1.width > o2.width) {
                    return -1;
                } else if (o1.width == o2.width) {
                    return o1.height > o2.height ? -1 : 1;
                } else {
                    return 1;
                }
            }
        });
        sizes = Arrays.asList(tempSizes);

        Camera.Size bestSize = sizes.get(0);
        float previewViewRatio;
        if (previewViewSize != null) {
            previewViewRatio = (float) previewViewSize.x / (float) previewViewSize.y;
        } else {
            previewViewRatio = (float) bestSize.width / (float) bestSize.height;
        }

        if (previewViewRatio > 1) {
            previewViewRatio = 1 / previewViewRatio;
        }
        boolean isNormalRotate = (additionalRotation % 180 == 0);

        for (Camera.Size s : sizes) {
            if (specificPreviewSize != null && specificPreviewSize.x == s.width && specificPreviewSize.y == s.height) {
                return s;
            }
            if (isNormalRotate) {
                if (Math.abs((s.height / (float) s.width) - previewViewRatio) < Math.abs(bestSize.height / (float) bestSize.width - previewViewRatio)) {
                    bestSize = s;
                }
            } else {
                if (Math.abs((s.width / (float) s.height) - previewViewRatio) < Math.abs(bestSize.width / (float) bestSize.height - previewViewRatio)) {
                    bestSize = s;
                }
            }
        }
        return bestSize;
    }



    private  void  resetCamera()
    {
        if(!isPreview)
        {
            camera.startPreview();
            isPreview=true;
        }
    }

    private int getCameraOri(int rotation) {
        int degrees = rotation * 90;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            default:
                break;
        }
        additionalRotation /= 90;
        additionalRotation *= 90;
        degrees += additionalRotation;
        int result;
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(rgbCameraID, info);
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }
    @Override
    protected void onPause() {
        super.onPause();
        if(camera!=null)
        {

            camera.stopPreview();
            camera.release();
        }
    }

    public Bitmap runInPreviewFrame(byte[] data, Camera camera){
        ByteArrayOutputStream baos;
        byte[] rawImage;
        Bitmap bitmap;

        Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        YuvImage yuvimage = new YuvImage(
                data,
                ImageFormat.NV21,
                previewSize.width,
                previewSize.height,
                null);
        baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
        rawImage = baos.toByteArray();
        //将rawImage转换成bitmap
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);
        return bitmap;

    }
}